import {Reducer,stateType, actionTypes} from "./createStore";
interface ReducersMap{
    [key:string]:Reducer
}
export default function combineReducers(reducers:ReducersMap){
    const reducerKeys = Object.keys(reducers)

    return function(state:stateType, action:actionTypes){
        let hasChanged = false
        const nextState:stateType = {}
        for (let i = 0; i < reducerKeys.length; i++) {
          const key = reducerKeys[i]
          const reducer = reducers[key]
          const previousStateForKey = state[key]
          const nextStateForKey = reducer(previousStateForKey, action)
          nextState[key] = nextStateForKey
          hasChanged = hasChanged || nextStateForKey !== previousStateForKey
        }
        return hasChanged ? nextState : state
    }
}